package indi.zhifa.recipe.bailan.framework.auth.filter;

import indi.zhifa.recipe.bailan.framework.auth.entity.annotations.auth.RequireRole;
import indi.zhifa.recipe.bailan.framework.auth.entity.BaseTokenObject;
import indi.zhifa.recipe.bailan.framework.auth.util.AuthConst;
import indi.zhifa.recipe.bailan.framework.auth.util.IBaseTokenUtil;
import indi.zhifa.recipe.bailan.framework.common.entity.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Order(value = 100)
@Slf4j
@Aspect
@RequiredArgsConstructor
@Component
public class RequireRoleAop {

    protected final IBaseTokenUtil mBaseTokenUtil;

    @Before("@annotation(permission)")
    public void before(JoinPoint point, RequireRole permission){
        BaseTokenObject baseTokenObject = mBaseTokenUtil.getTokenObject();
        // 获取用户的角色
        List<String> roles = baseTokenObject.getRoles();
        Set<String> roleSet = roles.stream().collect(Collectors.toSet());
        if(roleSet.contains(AuthConst.spAdmCode)){//超管角色直接跳过，不需要在每个注解中配置了
            return;
        }
        //便利所有的可通行的角色，如果用户有这个角色，则return
        String[] permitRoles = permission.roles();
        for(String permitRole : permitRoles){
            if(roleSet.contains(permitRole)){
                return;
            }
        }
        // 所有所需的角色都没有，那就报错
        throw new ServiceException("需要角色"+String.join(",",permitRoles));
    }
}
